package hn.cch.framework.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtil {

    /**
     * 处理xml转为map
     *
     * @param prefix
     * @param xml
     * @return
     */
    public static Map<String, Object> toMap(String prefix, String xml) {
        Map<String, Object> map = new HashMap<>();
        try {
            Document document = DocumentHelper.parseText(xml);
            Element element = document.getRootElement();
            String tag = element.getQualifiedName();
            map.putAll(toTag(tag, element));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 递归调用：处理tag转为map
     *
     * @param pre
     * @param element
     * @return
     */
    @SuppressWarnings(value = "unchecked")
    public static Map<String, Object> toTag(String pre, Element element) {
        Map<String, Object> map = new HashMap<>();
        if (element.isTextOnly()) {//
            map.put(pre + "." + element.getQualifiedName(), element.getTextTrim());
        } else {
            List<Element> elements = element.elements();
            List<Map<String, Object>> list = new ArrayList<>();
            for (Element ele : elements) {
                String tag = ele.getQualifiedName();
                List<Element>  all = element.elements(tag);
                if (all.size() > 1) {
                    list.add(toTag(pre + "." + tag, ele));
                } else {
                    map.putAll(toTag(pre + "." + tag, ele));
                }
            }
            if (list.size() > 0) {
                map.put(pre + ".", list);
            }
        }
        return map;
    }


}
